﻿using Forum.Model.Entity;
using Forum.Repository.Interface;

namespace Forum.MiddleWare
{
    /// <summary>
    /// 统计访问中间件
    /// </summary>
    public class VisitRecordMiddleware
    {
        private readonly RequestDelegate _next;

        public VisitRecordMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext context, IAppRepository<VisitRecord> visitRecordRepo)
        {
            var request = context.Request;
            var response = context.Response;
            if (request.Path.ToString().StartsWith("/chathub"))
            {
                return _next(context);//signalr通讯的不要记录到日志
            }
            visitRecordRepo.InsertAsync(new VisitRecord
            {
                Ip = "",
                RequestPath = request.Path,
                RequestQueryString = request.QueryString.Value,
                RequestMethod = request.Method,
                UserAgent = request.Headers.UserAgent,
                Time = DateTime.Now
            });

            return _next(context);
        }
    }
}
